<template>
	<view class="purchase-container">
		<view class="form-section">
				<view class="form-item">
					<text class="form-label">关联项目 <text class="required">*</text></text>
					<picker @change="onProjectChange" :value="projectIndex" :range="projectList" :disabled="isEdit">
						<view class="picker-input">
							<text>{{ projectList[projectIndex] }}</text>
							<text class="picker-arrow" v-if="!isEdit">></text>
						</view>
					</picker>
				</view>
			</view>
		<view class="form-section">
			
			<view class="purchase-items-section">
				<view class="section-header">
					<text class="section-title">采购物品列表</text>
					<view class="add-item-button" @tap="addPurchaseItem" v-if="!isEdit">
						<text class="add-icon">+</text>
						<text class="add-text">添加物品</text>
					</view>
				</view>
				
				<view class="purchase-item" v-for="(item, index) in purchaseItems" :key="index">
					<view class="item-header">
						<view class="item-title-section">
							<text class="item-number">{{ index + 1 }}</text>
							<text class="item-title">采购物品</text>
						</view>
						<text class="item-delete" @tap="deletePurchaseItem(index)" v-if="!isEdit">×</text>
					</view>
					
					<view class="item-content">
						<view class="form-item">
							<text class="form-label">物品名称 <text class="required">*</text></text>
							<input class="form-input" v-model="item.name" placeholder="请输入物品名称" :disabled="isEdit" />
						</view>

						<view class="form-item">
							<text class="form-label">规格参数 <text class="required">*</text></text>
							<input class="form-input" v-model="item.specification" placeholder="请输入规格参数" :disabled="isEdit" />
						</view>

						<view class="form-item">
							<text class="form-label">数量 <text class="required">*</text></text>
							<input class="form-input" type="number" v-model="item.quantity" placeholder="0" :disabled="isEdit" />
						</view>
						
						<view class="form-item">
							<text class="form-label">单位 <text class="required">*</text></text>
							<input class="form-input" v-model="item.unit" placeholder="个/件/台" :disabled="isEdit" />
						</view>

						<view class="form-item">
							<text class="form-label">预计金额 <text class="required">*</text></text>
							<input class="form-input" type="digit" v-model="item.amount" placeholder="0.00" :disabled="isEdit" />
						</view>
					</view>
				</view>
			</view>

			

			<view class="form-item">
				<text class="form-label">希望交付时间 <text class="required">*</text></text>
				<DateTimePicker v-model="deliveryTime" :disabled="isEdit" mode="date" />
			</view>

			<view class="form-item textarea-item">
				<text class="form-label">采购理由 <text class="required">*</text></text>
				<textarea class="form-textarea" v-model="reason" placeholder="请说明采购理由和用途" maxlength="200"
					:disabled="isEdit"></textarea>
				<text class="char-count">{{ reason.length }}/200</text>
			</view>

			<view class="form-item">
				<UploadAttachments 
					style="width: 100%;"
					v-model="uploadedFiles"
					label="说明附件"
					:disabled="isEdit"
					:max-count="5"
					:file-types="['jpg', 'jpeg', 'png']"
				/>
			</view>
		</view>

		<!-- 审批流程 -->
		<view class="approval-section">
			<text class="section-title">审批流程</text>
			<view class="approval-steps">
				<view v-if="approvalSteps.length > 0">
					<view class="approval-step" v-for="(step, index) in approvalSteps" :key="index">
						<view class="step-header">
							<view class="step-avatar">
								<text class="avatar-text">{{ step.user_name.charAt(0) }}</text>
							</view>
							<view class="step-info">
								<text class="step-name">{{ step.user_name }}</text>
								<text class="step-position">{{ step.position }}</text>
							</view>
							<text v-if="!isNew" :class="['step-status', getStepStatusClass(step.status)]">
								{{ getStepStatusText(step.status) }}
							</text>
						</view>
						<view class="step-content" v-if="step.comment">
							<text class="step-comment">{{ step.comment }}</text>
							<text class="step-time">{{ step.update_time }}</text>
						</view>
					</view>
				</view>
				<view v-else class="empty-approval">
					<view class="empty-icon">!</view>
					<text class="empty-text">审批流程未定义，请联系管理员</text>
				</view>
			</view>
		</view>

		<!-- 提交按钮 -->
		<view class="submit-section">
			<button v-if="!isEdit" class="submit-button" @tap="submitPurchase" :disabled="!canSubmit()">
				{{ approvalSteps.length > 0 ? '提交' : '审批流程未定义，无法提交' }}
			</button>
			<button class="cancel-button" @tap="cancelPurchase" v-if="isEdit && canCancel()">
				作废申请
			</button>
		</view>
	</view>
</template>

<script lang="ts" setup>
import { ref, computed } from 'vue'
import { onLoad } from '@dcloudio/uni-app'
import DateTimePicker from '@/components/DateTimePicker.vue'
import UploadAttachments from '@/components/UploadAttachments.vue'
import { getProjects, getCurrentToken } from '@/common/auth'
import config from '@/common/config'
import { purchaseApi } from '@/common/api'
import { uploadAttachments, formatFileSize } from '@/common/upload'

// TypeScript interfaces
interface PurchaseFile {
	name: string
	url: string
	path: string
	size: string
	type: string
}

interface PurchaseItem {
	name: string
	specification: string
	quantity: string
	unit: string
	amount: string
}

interface ApprovalStep {
	position: string
	user_name: string
	user_id: string
	status: string
	comment?: string
	update_time?: string
}

interface Project {
	project_id: string
	project_name: string
}

// 表单数据
const purchaseItems = ref<PurchaseItem[]>([{
	name: '',
	specification: '',
	quantity: '',
	unit: '',
	amount: ''
}])
const reason = ref<string>('')
const deliveryTime = ref<string>('')
const uploadedFiles = ref<PurchaseFile[]>([])

// 项目相关
const projects = getProjects() as Project[]
const projectIndex = ref<number>(0)
const projectList = ref<string[]>(projects.map((project) => project.project_name))
const workflow_id = ref<number>(0)
const region_company = ref<string>('')

// 是否为编辑/查看模式
const isEdit = ref<boolean>(false)
const purchaseId = ref<string>('')
const isNew = ref<boolean>(true)

// 审批流程
const approvalSteps = ref<ApprovalStep[]>([])

// 添加采购物品
const addPurchaseItem = () => {
	purchaseItems.value.push({
		name: '',
		specification: '',
		quantity: '',
		unit: '',
		amount: ''
	})
}

// 删除采购物品
const deletePurchaseItem = (index: number) => {
	if (purchaseItems.value.length > 1) {
		purchaseItems.value.splice(index, 1)
	} else {
		uni.showToast({
			title: '至少需要一个采购物品',
			icon: 'none'
		})
	}
}

// 获取步骤状态样式
const getStepStatusClass = (status: string): string => {
	const statusMap: Record<string, string> = {
		'pending': 'pending',
		'approved': 'approved',
		'rejected': 'rejected',
		'canceled': 'canceled'
	}
	return statusMap[status] || 'pending'
}

// 获取步骤状态文本
const getStepStatusText = (status: string): string => {
	const statusMap: Record<string, string> = {
		'pending': '待审批',
		'approved': '已通过',
		'rejected': '已拒绝',
		'canceled': '已取消'
	}
	return statusMap[status] || '待审批'
}

const onProjectChange = (e: any) => {
	projectIndex.value = e.detail.value
	// 更新审批人
	loadApprovers()
}

// 加载采购详情
const loadPurchaseDetail = async (id: string) => {
	try {
		uni.showLoading({
			title: '加载中...'
		})

		// 调用采购详情API
		const res = await purchaseApi.getDetail(id)

		if (res.success && res.data) {
			const detail = res.data

			// 设置表单数据
			purchaseItems.value = detail.items.map((item: any) => ({
				name: item.name,
				specification: item.specification || '',
				quantity: item.quantity,
				unit: item.unit || '',
				amount: item.amount
			}))
			reason.value = detail.reason
			deliveryTime.value = detail.delivery_time

			// 设置项目
			projectIndex.value = projects.findIndex((project) => project.project_id === detail.project_id)
			workflow_id.value = detail.workflow_id
			region_company.value = detail.region_company

			// 设置附件
			console.log('原始附件数据:', detail.attachments)
			if (detail.attachments && detail.attachments.length > 0) {
				uploadedFiles.value = detail.attachments.map((file: any) => {
					// 兼容不同的字段名
					const mappedFile = {
						name: file.file_name || file.name,
						url: file.url,
						path: file.path || file.url,
						size: file.file_size ? formatFileSize(file.file_size) : (file.size || '未知大小'),
						type: file.file_type || file.type
					}
					console.log('映射后的文件:', mappedFile)
					return mappedFile
				})

				console.log('最终uploadedFiles:', uploadedFiles.value)
			} else {
				// 重置附件列表
				uploadedFiles.value = []
				console.log('没有附件，重置为空数组')
			}

			// 设置审批流程
			if (detail.approval_process) {
				approvalSteps.value = detail.approval_process.map((process: any) => {
					const { records, approver } = process
					let status = 'pending'
					if (records && records.length > 0) {
						const lastRecord = records[records.length - 1]
						status = lastRecord.action
					}
					return ({
						position: approver.position || '审批人',
						user_name: approver.name,
						status: status,
						user_id: approver.uid
					})
				})
			}

			return detail
		} else {
			uni.showToast({
				title: '加载详情失败',
				icon: 'none'
			})
			return null
		}
	} catch (error) {
		console.error('加载采购详情失败:', error)
		uni.showToast({
			title: '加载详情失败',
			icon: 'none'
		})
	} finally {
		uni.hideLoading()
	}
}

// 页面加载
onLoad(async (options) => {
	if (options.id) {
		purchaseId.value = options.id
		isEdit.value = true
		isNew.value = false
		await loadPurchaseDetail(options.id)
	} else {
		isEdit.value = false
		isNew.value = true
		// 新增模式，加载审批人
		loadApprovers()
	}
})



const canSubmit = (): boolean => {
	return purchaseItems.value.every(item => !!item.name && !!item.specification && !!item.quantity && !!item.unit && !!item.amount) && 
		!!reason.value.trim() && !!deliveryTime.value && projectIndex.value >= 0 && 
		approvalSteps.value.length > 0
}

// 加载审批人列表
const loadApprovers = async () => {
	try {
		if (projects[projectIndex.value]) {
			uni.showLoading({
				title: '加载审批人...'
			})
			
			const projectId = projects[projectIndex.value].project_id
			// 调用获取审批人API
			const res = await purchaseApi.getApprovers(projectId, "purchase")
			
			uni.hideLoading()

			if (res.success && res.data.length > 0) {
				const approvalWorkflow = res.data[0]
				workflow_id.value = approvalWorkflow.id
				region_company.value = approvalWorkflow.region_company
				approvalSteps.value = approvalWorkflow.approval_process.map((approver: any) => ({
					position: approver.approver_position || '审批人',
					user_name: approver.approver_name,
					user_id: approver.approver_id
				}))
				console.log('审批人列表加载成功:', approvalSteps.value)
			} else {
				console.log('使用默认审批人列表')
				// 保持默认的审批人列表
			}
		}
	} catch (error) {
		uni.hideLoading()
		console.error('获取审批人列表失败:', error)

		// 显示错误提示，但不影响页面使用
		uni.showToast({
			title: '获取审批人失败，使用默认配置',
			icon: 'none',
			duration: 2000
		})
	}
}

const submitPurchase = async () => {
	if (!canSubmit()) {
		uni.showToast({
			title: '请完善申请信息',
			icon: 'none'
		})
		return
	}

	uni.showLoading({
		title: '提交中...'
	})

	try {
		// 准备提交的数据（先不包含附件）
		const submitData = {
			purchaseItems: purchaseItems.value.map(item => ({
				name: item.name,
				specification: item.specification,
				quantity: item.quantity,
				unit: item.unit,
				amount: item.amount
			})),
			reason: reason.value,
			delivery_time: deliveryTime.value,
			submitTime: new Date().toISOString(),
			region_company: region_company.value,
			workflow_id: workflow_id.value,
			project_id: projects[projectIndex.value].project_id
		}

		console.log('提交的采购数据:', submitData)

		uni.showLoading({
			title: '提交申请中...'
		})

		// 先提交表单数据
		const res = await purchaseApi.apply(submitData)
		
		if (!res.success) {
			uni.hideLoading()
			uni.showToast({
				title: res.message || '提交失败',
				icon: 'none',
				duration: 3000
			})
			return
		}

		// 获取申请ID
		const { purchase_id, approval_instance_id } = res.data

		// 如果有附件，再上传附件
		if (uploadedFiles.value.length > 0) {
			uni.showLoading({
				title: '上传附件中...'
			})

			try {
				// 转换文件格式
				const files = uploadedFiles.value.map(file => ({
					path: file.path,
					name: file.name,
					size: parseInt(file.size) || 0,
					type: file.type
				}));	

				// 使用通用上传工具上传文件，支持并行上传
				const uploadedAttachments = await uploadAttachments(				
					files,
					true, // 并行上传
					{
						type: "attachment",
						relation_id: purchase_id, // 传递申请ID
						relation_type: "purchase", // 传递申请类型
						approval_instance_id: approval_instance_id // 传递审批实例ID
					},
					(current, total) => {
						// 更新上传进度
						uni.showLoading({
							title: `上传中 ${current}/${total}`
						});
					}
				);

				// 如果需要，可以调用更新附件API
				if (uploadedAttachments.length > 0) {
					const attachments = uploadedAttachments.map(file => ({
						path: file.path,
						size: String(file.size),
						type: file.type,
						url: file.url
					}));

					// 可选：调用更新附件API
					// await purchaseApi.updateAttachments(purchase_id, attachments);
				}
			} catch (error: any) {
				console.error('文件上传失败:', error)
				uni.showToast({
					title: '部分附件上传失败，请在详情页重新上传',
					icon: 'none',
					duration: 2000
				})
				// 继续流程，不影响已提交的申请
			}
		}

		uni.hideLoading()

		uni.showToast({
			title: '申请提交成功',
			icon: 'success'
		})

		// 清空表单
		purchaseItems.value = [{
			name: '',
			specification: '',
			quantity: '',
			unit: '',
			amount: ''
		}]
		reason.value = ''
		deliveryTime.value = ''
		uploadedFiles.value = []

		// 跳转到首页
		uni.switchTab({
			url: '/pages/home/home'
		})
	} catch (error: any) {
		uni.hideLoading()
		console.error('提交失败:', error)
		uni.showToast({
			title: error.message || '网络错误，请稍后重试',
			icon: 'none',
			duration: 3000
		})
	}
}

// 判断是否可以作废
const canCancel = (): boolean => {
	if (isNew.value) {
		return false
	}
	// 只有待审批状态的采购申请才能作废
	return approvalSteps.value.length > 0 &&
		approvalSteps.value[0].status === 'pending'
}

// 作废采购申请
const cancelPurchase = async () => {
	try {
		uni.showModal({
			title: '确认作废',
			content: '确定要作废该采购申请吗？',
			success: async (res: { confirm: boolean }) => {
				if (res.confirm) {
					uni.showLoading({
						title: '处理中...'
					})

					// 调用作废采购API
					const res = await purchaseApi.cancel(purchaseId.value)
					
					uni.hideLoading()

					if (res.success) {
						uni.showToast({
							title: '作废成功',
							icon: 'success'
						})

						uni.switchTab({
							url: '/pages/home/home'
						})
					} else {
						uni.showToast({
							title: res.message || '作废失败',
							icon: 'none'
						})
					}
				}
			}
		})
	} catch (error: any) {
		uni.hideLoading()
		console.error('作废失败:', error)
		uni.showToast({
			title: error.message || '网络错误，请稍后重试',
			icon: 'none'
		})
	}
}
</script>

<style scoped>
.purchase-container {
	padding: 0;
	background-color: #f5f6fa;
	min-height: 100vh;
}

.form-section {
	background: white;
	border-radius: 0;
	padding: 0;
	margin-bottom: 16rpx;
	box-shadow: none;
}

.purchase-items-section {
	margin-bottom: 16rpx;
}

.section-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 24rpx 32rpx;
	border-bottom: 1rpx solid #f0f0f0;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
}

.add-item-button {
	display: flex;
	align-items: center;
	justify-content: center;
	color: #2B5BA1;
	font-size: 28rpx;
	background: linear-gradient(135deg, #e3f2fd 0%, #f3e5f5 100%);
	border: 2rpx solid #2B5BA1;
	border-radius: 24rpx;
	padding: 12rpx 20rpx;
	transition: all 0.3s ease;
	box-shadow: 0 2rpx 8rpx rgba(43, 91, 161, 0.1);
}

.add-item-button:active {
	transform: scale(0.95);
	background: linear-gradient(135deg, #bbdefb 0%, #e1bee7 100%);
	box-shadow: 0 1rpx 4rpx rgba(43, 91, 161, 0.2);
}

.add-icon {
	margin-right: 8rpx;
	font-weight: bold;
	font-size: 32rpx;
	line-height: 1;
}

.purchase-item {
	background: white;
	border-radius: 0;
	margin: 0;
	padding: 0;
	box-shadow: none;
	border: none;
}

.item-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 28rpx 32rpx;
	border-bottom: 1rpx solid #f0f0f0;
	background: linear-gradient(135deg, #f8f9fa 0%, #f1f3f4 100%);
	border-radius: 0;
	position: relative;
}

.item-header::before {
	content: '';
	position: absolute;
	left: 0;
	top: 0;
	bottom: 0;
	width: 6rpx;
	background: linear-gradient(180deg, #2B5BA1 0%, #1976d2 100%);
	border-radius: 0 4rpx 4rpx 0;
}

.item-title-section {
	display: flex;
	align-items: center;
}

.item-number {
	width: 44rpx;
	height: 44rpx;
	background: linear-gradient(135deg, #2B5BA1 0%, #1976d2 100%);
	color: white;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 26rpx;
	font-weight: bold;
	margin-right: 16rpx;
	box-shadow: 0 2rpx 8rpx rgba(43, 91, 161, 0.2);
	border: 2rpx solid rgba(255, 255, 255, 0.3);
}

.item-title {
	font-size: 30rpx;
	font-weight: 600;
	color: #2c3e50;
	text-shadow: 0 1rpx 2rpx rgba(0, 0, 0, 0.05);
}

.item-delete {
	font-size: 32rpx;
	color: #ff6b6b;
	width: 56rpx;
	height: 56rpx;
	display: flex;
	align-items: center;
	justify-content: center;
	background: linear-gradient(135deg, #fff5f5 0%, #ffe8e8 100%);
	border: 2rpx solid #ff6b6b;
	border-radius: 50%;
	transition: all 0.3s ease;
	box-shadow: 0 2rpx 8rpx rgba(255, 107, 107, 0.1);
	font-weight: bold;
}

.item-delete:active {
	transform: scale(0.9);
	background: linear-gradient(135deg, #ffe0e0 0%, #ffd6d6 100%);
	box-shadow: 0 1rpx 4rpx rgba(255, 107, 107, 0.2);
}

.item-content {
	padding: 0;
}

.form-item {
	padding: 24rpx 32rpx;
	border-bottom: 1rpx solid #f0f0f0;
	margin-bottom: 0;
	display: flex;
	justify-content: space-between;
	align-items: center;
	min-height: 88rpx;
}

.form-item:last-child {
	border-bottom: none;
}

.form-item.textarea-item {
	flex-direction: column;
	align-items: stretch;
	min-height: auto;
}

.form-label {
	font-size: 28rpx;
	color: #333;
	margin-bottom: 0;
	display: block;
	flex-shrink: 0;
}

.form-input {
	flex: 1;
	text-align: right;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	font-size: 28rpx;
	max-width: 400rpx;
}

.form-textarea {
	width: 100%;
	box-sizing: border-box;
	min-height: 120rpx;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	font-size: 28rpx;
	line-height: 1.5;
	margin-top: 16rpx;
}

.char-count {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 8rpx;
	display: block;
}





.required {
	color: #f44336;
	font-size: 28rpx;
}





.picker-input {
	display: flex;
	justify-content: space-between;
	align-items: center;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	min-height: 48rpx;
	flex: 1;
	max-width: 400rpx;
}

.picker-arrow {
	color: #999;
	margin-left: 8rpx;
}

.form-textarea {
	width: 100%;
	box-sizing: border-box;
	min-height: 120rpx;
	padding: 0;
	border: none;
	border-radius: 0;
	background: transparent;
	font-size: 28rpx;
	line-height: 1.5;
	margin-top: 16rpx;
}

.char-count {
	font-size: 24rpx;
	color: #999;
	text-align: right;
	margin-top: 8rpx;
	display: block;
}



.approval-section {
	background: white;
	border-radius: 0;
	padding: 32rpx;
	margin-bottom: 16rpx;
	box-shadow: none;
}

.section-title {
	font-size: 32rpx;
	font-weight: 600;
	color: #333;
	margin-bottom: 16rpx;
	display: block;
}

.approval-steps {
	margin-top: 24rpx;
}

.approval-step {
	background: #f8f9fa;
	border-radius: 12rpx;
	padding: 24rpx;
	margin-bottom: 16rpx;
}

.step-header {
	display: flex;
	align-items: center;
	margin-bottom: 16rpx;
}

.step-avatar {
	width: 64rpx;
	height: 64rpx;
	border-radius: 50%;
	background: #2B5BA1;
	color: white;
	display: flex;
	align-items: center;
	justify-content: center;
	font-size: 24rpx;
	font-weight: bold;
	margin-right: 16rpx;
}

.avatar-text {
	color: white;
}

.step-info {
	flex: 1;
}

.step-name {
	font-size: 28rpx;
	color: #333;
	font-weight: 500;
	display: block;
}

.step-position {
	font-size: 24rpx;
	color: #666;
}

.step-status {
	font-size: 24rpx;
	padding: 4rpx 12rpx;
	border-radius: 8rpx;
}

.step-status.pending {
	color: #2196f3;
	background: #e3f2fd;
}

.step-status.approved {
	color: #4caf50;
	background: #e8f5e9;
}

.step-status.rejected {
	color: #f44336;
	background: #ffebee;
}

.step-status.canceled {
	color: #9e9e9e;
	background: #f5f5f5;
}

.step-content {
	margin-top: 16rpx;
	padding-top: 16rpx;
	border-top: 1rpx solid #eee;
}

.step-comment {
	font-size: 28rpx;
	color: #333;
	display: block;
	margin-bottom: 8rpx;
}

.step-time {
	font-size: 24rpx;
	color: #999;
}

.submit-section {
	padding: 32rpx;
	margin-bottom: 0;
}

.submit-button {
	width: 100%;
	background: #2B5BA1;
	color: white;
	border: none;
	border-radius: 12rpx;
	padding: 6rpx;
	font-size: 32rpx;
	font-weight: 500;
}

.submit-button[disabled] {
	background: #ccc;
}

.cancel-button {
	width: 100%;
	background: #f44336;
	color: white;
	border: none;
	border-radius: 12rpx;
	padding: 6rpx;
	font-size: 32rpx;
	font-weight: 500;
	margin-top: 16rpx;
}

.cancel-button[disabled] {
	background: #ccc;
}

.empty-approval {
	display: flex;
	flex-direction: column;
	align-items: center;
	padding: 40rpx 0;
	background-color: #fff5f5;
	border: 1rpx dashed #ffccc7;
	border-radius: 12rpx;
	margin: 16rpx 0;
}

.empty-icon {
	width: 80rpx;
	height: 80rpx;
	background-color: #fff2f0;
	border-radius: 50%;
	display: flex;
	align-items: center;
	justify-content: center;
	color: #ff4d4f;
	font-size: 48rpx;
	font-weight: bold;
	margin-bottom: 16rpx;
}

.empty-text {
	text-align: center;
	color: #ff4d4f;
	font-size: 28rpx;
}
</style> 